package cn.edu.swu.game;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;
import java.util.List;


/*
{
    "games": [
        {"id": 1, "name": "c program", "company":"tom", "price": 33, "describe": "good game", "picture": "./upload/1111.jpg"},
        {"id": 2, "name": "R program", "company":"jerry", "price": 33, "describe": "good game", "picture": "./upload/22222.jpg"}
    ]
}
 */

@WebServlet("/api/games")
public class ListGameApi extends HttpServlet  {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            List<Game> games = GameRepo.getInstance().getAll();
            response.setContentType("application/json; charset=UTF-8");
            try (Writer writer = response.getWriter()) {
                this.writeJsonByJackson(response.getWriter(), games);
            }
        } catch (SQLException e) {
            throw new IOException(e);
        }
    }

    private void writeJsonByJackson(Writer writer, List<Game> games)  throws IOException  {
        String json = new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(games);
        writer.write(json);
    }

    private void writeJson(Writer writer, List<Game> games) throws IOException {
        writer.write("{");
        writer.write("\"games\":[");
        for (int i=0; i<games.size(); i++) {
            if (i > 0) writer.write(",");
            Game game = games.get(i);
            writer.write(String.format(
                    "{\"id\":%s, \"name\":\"%s\", \"company\":\"%s\", \"price\":%s, \"describe\":\"%s\", \"picture\":\"%s\"}",
                    game.getId(), game.getName(),game.getCompany(), game.getPrice(), game.getDescribe(), game.getPicture()
            ));
        }
        writer.write("]");
        writer.write("}");
    }

}
